# -*- coding: UTF-8 -*-
from parse import analyse
from gevent.pywsgi import WSGIServer
from gevent import monkey
import json
import numpy as np

from time import sleep

from flask import Flask, request, jsonify, Response, render_template

monkey.patch_all()

app = Flask(__name__)
app.debug = True

# @app.route( '/', methods=['get'])
# def hello():
#     return render_template('index.html', input_text = '', res_text = '')


@app.route( '/dbpnb', methods=['post'])
def dbpnb():
    layoutPath = request.form.get('layoutPath')
    imagePath = request.form.getlist('imagePath[]')
    fontPath = request.form.get('fontPath')
    pageBackgroundImage = request.form.get('pageBackgroundImage')
    pageBackgroundColor = request.form.getlist('pageBackgroundColor[]')

    result = analyse(
        layoutPath = layoutPath,
        imagePath = imagePath,
        fontPath = fontPath,
        pageBackgroundImage = pageBackgroundImage,
        pageBackgroundColor = pageBackgroundColor
    )
    return Response ( json.dumps(result, cls=NpEncoder) , mimetype = 'application/json' )



class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)

if __name__ == '__main__':
    http_server = WSGIServer(('127.0.0.1', 7777), app)
    http_server.serve_forever()